package com.td.erhome.ui.login;


import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.td.erhome.R;
import com.td.erhome.base.BaseActivity;
import com.td.erhome.models.BaseBean;
import com.td.erhome.models.User;
import com.td.erhome.net.Api;
import com.td.erhome.net.BaseSubscriber;
import com.td.erhome.ui.article.ArticleContentActivity;
import com.td.erhome.ui.home.HomeActivity;
import com.td.erhome.utils.AppUtils;
import com.td.erhome.utils.ConstUtils;
import com.td.erhome.utils.RxBus;
import com.td.erhome.utils.T;
import com.td.erhome.utils.TextUtil;
import com.td.erhome.utils.UserManager;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class LoginActivity extends BaseActivity implements Handler.Callback{

    @Bind(R.id.tv_get_code)
    TextView mTvGetCode;
    @Bind(R.id.et_name)
    EditText mEtName;
    @Bind(R.id.tv_password)
    EditText mTvPassword;
    @Bind(R.id.ll_login)
    LinearLayout mLlLogin;
    @Bind(R.id.tv_sure)
    TextView mTvSure;
    @Bind(R.id.img_login_wx)
    ImageView mImgLoginWx;
    @Bind(R.id.img_back)
    ImageView mImgBack;
    @Bind(R.id.tv_deal)
    TextView mTvDeal;
    private CountDownTimer mTimer;

    private static final int MSG_AUTH_CANCEL = 1;
    private static final int MSG_AUTH_ERROR= 2;
    private static final int MSG_AUTH_COMPLETE = 3;
    private Handler handler = new Handler(this);

    @Override
    protected int getLayoutId() {

        return R.layout.activity_login;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void releaseResource() {
        if (mTimer!=null){
            mTimer.cancel();
        }

    }

    @OnClick({R.id.tv_get_code, R.id.tv_sure, R.id.img_login_wx,R.id.img_back,R.id.tv_deal})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_get_code:
                if (TextUtil.isPhone(mEtName.getText().toString())){
                    mTimer = new CountDownTimer(60000,1000){
                        @Override
                        public void onTick(long millisUntilFinished) {
                            mTvGetCode.setText(millisUntilFinished/1000+"s");
                        }
                        @Override
                        public void onFinish() {
                            mTvGetCode.setClickable(true);
                            mTvGetCode.setText("重新获取");
                        }
                    };
                    getCode();
                }
                else {
                    T.showLong(this,"请输入正确手机号码");
                }

                break;
            case R.id.tv_sure:
                checkLoginCaptcha();
                break;
            case R.id.img_login_wx:
             if (!AppUtils.isInstallApp(this,"com.tencent.mm")){
                 T.showLong(this,"请安装微信客户端");
                 return;
             }

                wxLogin();
                break;
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_deal:
                Intent intent = new Intent(this, ArticleContentActivity.class);
                intent.putExtra("url","http://sifangtengda.top/login_agreement.html");
                intent.putExtra("title","四方腾达用户协议");
                startActivity(intent);
                break;
        }
    }
    public void getCode(){

        HashMap<String, Object> params = new HashMap<>();
        params.put("mobile",  mEtName.getText().toString());
        params.put("client_id", "t7vgeehvhcg40sks");
        Api.getRetrofit().sendLoginCaptcha(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<BaseBean>(LoginActivity.this){
                    @Override
                    public void onNext(BaseBean baseBean) {
                        super.onNext(baseBean);
                        mTvGetCode.setClickable(false);
                        mTimer.start();
                    }
                });
    }

    //登录
    public void checkLoginCaptcha(){
        if (TextUtil.isEditTextEmpty(mEtName)){
            T.showLong(this,"请输入手机号码");
            return;
        }

        if (TextUtil.isEditTextEmpty(mTvPassword)){
            T.showLong(this,"请输入验证码");
            return;
        }

        HashMap<String, Object> params = new HashMap<>();
        params.put("mobile",  mEtName.getText().toString());
        params.put("client_id", "t7vgeehvhcg40sks");
        params.put("captcha", mTvPassword.getText().toString());
        Api.getRetrofit().checkLoginCaptcha(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                 .subscribe(new BaseSubscriber<BaseBean<User>>(LoginActivity.this){
                     @Override
                     public void onNext(BaseBean<User> userBaseBean) {
                         super.onNext(userBaseBean);
                          UserManager.getIns().saveUserInfo(userBaseBean.getData()); //保存用户信息
                          startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                          RxBus.getInstance().post(ConstUtils.LOGOUT);
                          finish();
                     }
                 });
    }

    //微信登录授权
    public void wxLogin(){

        Platform plat = ShareSDK.getPlatform(this, Wechat.NAME);
        if (plat == null) {
            return;
        }
        if (plat.isAuthValid()) {
            plat.removeAccount(true);
            return;
        }
        //使用SSO授权，通过客户单授权(true不使用)
        plat.SSOSetting(false);
        plat.setPlatformActionListener(new PlatformActionListener() {
            public void onComplete(Platform plat, int action, HashMap<String, Object> res) {
                if (action == Platform.ACTION_USER_INFOR) {
                    Message msg = new Message();
                    msg.what = MSG_AUTH_COMPLETE;
                    msg.arg2 = action;
                    msg.obj =  new Object[] {plat.getName(), res};
                    handler.sendMessage(msg);
                }
            }

            public void onError(Platform plat, int action, Throwable t) {
                if (action == Platform.ACTION_USER_INFOR) {
                    Message msg = new Message();
                    msg.what = MSG_AUTH_ERROR;
                    msg.arg2 = action;
                    msg.obj = t;
                    handler.sendMessage(msg);
                }
                t.printStackTrace();
            }

            public void onCancel(Platform plat, int action) {
                if (action == Platform.ACTION_USER_INFOR) {
                    Message msg = new Message();
                    msg.what = MSG_AUTH_CANCEL;
                    msg.arg2 = action;
                    msg.obj = plat;
                    handler.sendMessage(msg);
                }
            }
        });
        plat.authorize();
        plat.showUser(null);

    }


    /**处理操作结果*/
    public boolean handleMessage(Message msg) {
        switch(msg.what) {
            case MSG_AUTH_CANCEL:
                // 取消
                Toast.makeText(this, "取消授权", Toast.LENGTH_SHORT).show();
            break;
            case MSG_AUTH_ERROR:
                // 失败
                Throwable t = (Throwable) msg.obj;
                String text = "caught error: " + t.getMessage();
                Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
                t.printStackTrace();
             break;
            case MSG_AUTH_COMPLETE:
                // 成功
                Object[] objs = (Object[]) msg.obj;
                String platform = (String) objs[0];
                @SuppressWarnings("unchecked")
                HashMap<String, Object> res = (HashMap<String, Object>) objs[1];

                Platform pla = ShareSDK.getPlatform(platform);
                //第三方头像
                String mUserIcon = pla.getDb().getUserIcon();
                //第三方ID
                final String  mUserId = pla.getDb().getUserId();
                //第三方姓名
                String  mUserName = pla.getDb().getUserName();
                //性别
                String  gender = pla.getDb().getUserGender();

                HashMap<String, Object> params = new HashMap<>();
                params.put("openid", mUserId);
                params.put("nickname", mUserName);
                params.put("sex",gender);
                params.put("headimgurl", mUserIcon);
                params.put("client_id", "t7vgeehvhcg40sks");
                Api.getRetrofit().uploadWechatInfo(params)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseSubscriber<BaseBean<User>>(LoginActivity.this){
                            @Override
                            public void onNext(BaseBean<User> userBaseBean) {
                                super.onNext(userBaseBean);
                                User data = userBaseBean.getData();
                                if (data.is_need_bind_account.equals("1")){
                                    Intent intent = new Intent(LoginActivity.this,BindPhoneActivity.class);
                                    intent.putExtra("open_id",data.open_id);
                                    startActivity(intent);
                                    finish();
                                }else {
                                    UserManager.getIns().saveUserInfo(userBaseBean.getData()); //保存用户信息
                                    startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                                    RxBus.getInstance().post(ConstUtils.LOGOUT);
                                    finish();
                                }

                                finish();
                            }
                        });

             break;
        }
        return false;
    }

}
